package com.rds.workflow.service.impl;

import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.core.domain.entity.SysUser;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.system.mapper.SysUserMapper;
import com.rds.system.service.IRdaStateService;
import com.rds.system.service.ISysHistoryService;
import com.rds.workflow.domain.*;
import com.rds.workflow.mapper.*;
import com.rds.workflow.service.RdaWorkflowTempleteScopeService;
import com.rds.workflow.utils.WorkflowStateid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class RdaWorkflowTempleteScopeServiceImp implements RdaWorkflowTempleteScopeService {

    /** 文档表名 */
    private static final String tableName = "rda_document";

    @Autowired
    private RdaWorkflowTempleteScopeMapper rdaWorkflowTempleteScopeMapper;

    @Autowired
    private RdaWorkflowMapper rdaWorkflowMapper;

    @Autowired
    private RdaNodeTempleteMapper rdaNodeTempleteMapper;

    @Autowired
    private RdaWfNodeMapper rdaWfNodeMapper;

    @Autowired
    private RdaWorkflow2NodeTempleteRelMapper rdaWorkflow2NodeTempleteRelMapper;

    @Autowired
    private RdaWorkflow2NodeRelMapper rdaWorkflow2NodeRelMapper;

    @Autowired
    private RdaWorkflowObjectRelMapper rdaWorkflowObjectRelMapper;

    @Autowired
    private ISysHistoryService sysHistoryService;

    @Autowired
    private IDynamicService dynamicService;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RdaWfTaskMapper rdaWfTaskMapper;

    @Autowired
    private RdaNode2TaskRelMapper rdaNode2TaskRelMapper;

    @Autowired
    private RdaWfNodeAgentRelMapper rdaWfNodeAgentRelMapper;

    @Autowired
    private RdaWfUserAgentMapper rdaWfUserAgentMapper;

    @Autowired
    private RdaWorkflowTempleteMapper rdaWorkflowTempleteMapper;



    @Override
    public RdaWorkflowTempleteScope selectRdaWorkflowTempleteScopeById(Long id) {
        return rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeById(id);
    }

    @Override
    public List<RdaWorkflowTempleteScope> selectRdaWorkflowTempleteScopeList(RdaWorkflowTempleteScope rdaWorkflowTempleteScope) {
        return rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeList(rdaWorkflowTempleteScope);
    }

    @Override
    public List<RdaWorkflowTempleteScope> selectRdaWorkflowTempleteScopeObject(Long objectTypeid,Long objectPolicyid,Long objectStateid) {
        return rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeObject(objectTypeid,objectPolicyid);
    }

    @Override
    public int insertRdaWorkflowTempleteScope(RdaWorkflowTempleteScope rdaWorkflowTempleteScope) {
        int row=rdaWorkflowTempleteScopeMapper.insertRdaWorkflowTempleteScope(rdaWorkflowTempleteScope);
        return row;
    }

    @Override
    public int updateRdaWorkflowTempleteScope(RdaWorkflowTempleteScope rdaWorkflowTempleteScope) {
        return rdaWorkflowTempleteScopeMapper.updateRdaWorkflowTempleteScope(rdaWorkflowTempleteScope);
    }

    @Override
    public int deleteRdaWorkflowTempleteScope(Long[] ids) {
        return rdaWorkflowTempleteScopeMapper.deleteRdaWorkflowTempleteScope(ids);
    }


    /**
     *  创建流程接口
     * @param objectTypeid   类型
     * @param objectPolicyid 策略
     * @param objectStateid  状态
     * @param objectId       对象id
     * @param objectModuleName 对象所属模块
     * @param ObjectName      对象名
     */
    @Override
    public AjaxResult createWorkflowWithObject(Long objectTypeid, Long objectPolicyid, Long objectStateid, Long objectId,String objectModuleName,String ObjectName) {
//        List<RdaWorkflowTempleteScope> list=rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeObject(objectTypeid,objectPolicyid);
        //2022-01-13去除状态查询
        List<RdaWorkflowTempleteScope> list=rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeObject(objectTypeid,objectPolicyid);
        String url="";
        String params="";
        String tableName="";
        if("document".equals(objectModuleName)){//文档接入流程

        }else if("wbs".equals(objectModuleName)){//wbs门接入流程
            url="/pmswbs/"+objectId;
            params="{'route':'details','treeMenu':'type_WBS'}";
            tableName="rda_pmswbs";
        }else if("projectChangeWF".equals(objectModuleName) || "projectPlayCut".equals(objectModuleName)){//变更流程接入流程
            url="/projectWorkflow/query/"+objectId;
            params="{'route':'details','treeMenu':'type_project_workflow'}";
            tableName="rda_project_workflow";
        }else if("reimbursement".equals(objectModuleName)){//报销接入流程
            url="/reimbursement/user/"+objectId;
            params="{'route':'details','treeMenu':'type_reimbursement'}";
            tableName="rda_memberlist_user";
        }else if("airticketApply".equals(objectModuleName)){//机票申请接入流程
            url="/reimbursement/airticketApply/"+objectId;
            params="{'route':'details','treeMenu':'type_airticket'}";
            tableName="rda_airticket_apply";
        }

        for(RdaWorkflowTempleteScope rdaWorkflowTempleteScope2:list){
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            Long id= SnowFlakeUtils.nextId();
            rdaWorkflow.setId(id);
            rdaWorkflow.setOwnerid(SecurityUtils.getUserId().intValue());
            rdaWorkflow.setTypeid(WorkflowStateid.workflowTypeid.intValue());
            rdaWorkflow.setPolicyid(WorkflowStateid.workflowPolicyid.intValue());
            rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
            rdaWorkflow.setFlowTempleteid(rdaWorkflowTempleteScope2.getWorkflowtempleteid());
            rdaWorkflow.setName(ObjectName+"-"+rdaWorkflowTempleteScope2.getName());
            rdaWorkflow.setDescription(rdaWorkflowTempleteScope2.getDescription());
            insertRdaWorkflow(rdaWorkflow,url,params);

            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(id);
            rdaWorkflowObjectRel.setObjectid(objectId);
            //2022-01-17更改为取流程模板应用范围里的 类型、策略、状态 start
            rdaWorkflowObjectRel.setObjectTypeid(rdaWorkflowTempleteScope2.getObjectTypeid());
            rdaWorkflowObjectRel.setObjectPolicyid(rdaWorkflowTempleteScope2.getObjectPolicyid());
            rdaWorkflowObjectRel.setObjectStateid(rdaWorkflowTempleteScope2.getObjectStateid());
            //2022-01-17更改为取流程模板应用范围里的 类型、策略、状态 end
            rdaWorkflowObjectRel.setObjectModuleName(objectModuleName);
            rdaWorkflowObjectRel.setPurpose("approve");
            rdaWorkflowObjectRelMapper.insertRdaWorkflowObjectRel(rdaWorkflowObjectRel);
            //自动启动流程控制开关
            if("1".equals(rdaWorkflowTempleteScope2.getStartUp())){
                return documentStartUpWorkflowList(objectId);
            }
        }
        return AjaxResult.success();
    }

    /**
     *  选中流程接口
     * @param objectTypeid   类型
     * @param objectPolicyid 策略
     * @param objectStateid 状态
     * @param worfklowId   流程模板id
     * @param objectId       对象id
     * @param objectModuleName   所属模块
     * @param objectName      对象名
     */
    @Override
    public AjaxResult createWorkflowWithObject(Long objectTypeid, Long objectPolicyid, Long objectStateid,Long worfklowId,Long objectId,String objectModuleName,String objectName) {
        String url="",params="",tableName="";
        if("document".equals(objectModuleName)){//文档接入流程

        }else if("wbs".equals(objectModuleName)){//wbs门接入流程
            url="/pmswbs/"+objectId;
            params="{'route':'details','treeMenu':'type_WBS'}";
            tableName="rda_pmswbs";
        }else if("projectChangeWF".equals(objectModuleName) || "projectPlayCut".equals(objectModuleName)){//变更流程接入流程
            url="/projectWorkflow/query/"+objectId;
            params="{'route':'details','treeMenu':'type_project_workflow'}";
            tableName="rda_project_workflow";
        }else if("reimbursement".equals(objectModuleName)){//报销接入流程
            url="/reimbursement/user/"+objectId;
            params="{'route':'details','treeMenu':'type_reimbursement'}";
            tableName="rda_memberlist_user";
        }else if("airticketApply".equals(objectModuleName)){//机票申请接入流程
            url="/reimbursement/airticketApply/"+objectId;
            params="{'route':'details','treeMenu':'type_airticket'}";
            tableName="rda_airticket_apply";
        }
        RdaWorkflowTemplete rdaWorkflowTemplete=rdaWorkflowTempleteMapper.selectRdaWorkflowTempleteById(worfklowId);
        RdaWorkflow rdaWorkflow=new RdaWorkflow();
        Long id= SnowFlakeUtils.nextId();
        rdaWorkflow.setId(id);
        rdaWorkflow.setOwnerid(SecurityUtils.getUserId().intValue());
        rdaWorkflow.setTypeid(WorkflowStateid.workflowTypeid.intValue());
        rdaWorkflow.setPolicyid(WorkflowStateid.workflowPolicyid.intValue());
        rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
        rdaWorkflow.setFlowTempleteid(worfklowId);
        rdaWorkflow.setName(objectName+"-"+rdaWorkflowTemplete.getName());
        rdaWorkflow.setDescription(objectName);
        insertRdaWorkflow(rdaWorkflow,url,params);

        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setWorkflowid(id);
        rdaWorkflowObjectRel.setObjectid(objectId);
        rdaWorkflowObjectRel.setObjectTypeid(objectTypeid);
        rdaWorkflowObjectRel.setObjectPolicyid(objectPolicyid);
        rdaWorkflowObjectRel.setObjectStateid(objectStateid);
        rdaWorkflowObjectRel.setObjectModuleName(objectModuleName);
        rdaWorkflowObjectRel.setPurpose("approve");
        rdaWorkflowObjectRelMapper.insertRdaWorkflowObjectRel(rdaWorkflowObjectRel);
        return AjaxResult.success();
    }

    /**
     *  根据部门匹配流程模板
     * @param objectTypeid   类型
     * @param objectPolicyid 策略
     * @param objectStateid  状态
     * @param objectId       对象id
     * @param objectModuleName 对象所属模块
     * @param ObjectName      对象名
     * @param deptId          部门
     */
    @Override
    public AjaxResult createWorkflowWithObject(Long objectTypeid, Long objectPolicyid, Long objectStateid, Long objectId,String objectModuleName,String ObjectName,Long deptId) {
        String url="",params="",tableName="";
        if("document".equals(objectModuleName)){//文档接入流程

        }else if("wbs".equals(objectModuleName)){//wbs门接入流程
            url="/pmswbs/"+objectId;
            params="{'route':'details','treeMenu':'type_WBS'}";
            tableName="rda_pmswbs";
        }else if("projectChangeWF".equals(objectModuleName) || "projectPlayCut".equals(objectModuleName)){//变更流程接入流程
            url="/projectWorkflow/query/"+objectId;
            params="{'route':'details','treeMenu':'type_project_workflow'}";
            tableName="rda_project_workflow";
        }else if("reimbursement".equals(objectModuleName)){//报销接入流程
            url="/reimbursement/user/"+objectId;
            params="{'route':'details','treeMenu':'type_reimbursement'}";
            tableName="rda_memberlist_user";
        }else if("airticketApply".equals(objectModuleName)){//机票申请接入流程
            url="/reimbursement/airticketApply/"+objectId;
            params="{'route':'details','treeMenu':'type_airticket'}";
            tableName="rda_airticket_apply";
        }
        RdaWorkflowTempleteScope rdaWorkflowTempleteScope=new RdaWorkflowTempleteScope();
        rdaWorkflowTempleteScope.setObjectTypeid(objectTypeid);
        rdaWorkflowTempleteScope.setObjectPolicyid(objectPolicyid);
        rdaWorkflowTempleteScope.setObjectDeptid(deptId);
        List<RdaWorkflowTempleteScope> list=rdaWorkflowTempleteScopeMapper.selectRdaWorkflowTempleteScopeList(rdaWorkflowTempleteScope);

        for(RdaWorkflowTempleteScope rdaWorkflowTempleteScope2:list){
            RdaWorkflow rdaWorkflow=new RdaWorkflow();
            Long id= SnowFlakeUtils.nextId();
            rdaWorkflow.setId(id);
            rdaWorkflow.setOwnerid(SecurityUtils.getUserId().intValue());
            rdaWorkflow.setTypeid(WorkflowStateid.workflowTypeid.intValue());
            rdaWorkflow.setPolicyid(WorkflowStateid.workflowPolicyid.intValue());
            rdaWorkflow.setStateid(WorkflowStateid.workflowCreateid.intValue());
            rdaWorkflow.setFlowTempleteid(rdaWorkflowTempleteScope2.getWorkflowtempleteid());
            rdaWorkflow.setName(ObjectName+"-"+rdaWorkflowTempleteScope2.getName());
            rdaWorkflow.setDescription(rdaWorkflowTempleteScope2.getDescription());
            insertRdaWorkflow(rdaWorkflow,url,params);

            RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
            rdaWorkflowObjectRel.setWorkflowid(id);
            rdaWorkflowObjectRel.setObjectid(objectId);
            //2022-01-17更改为取流程模板应用范围里的 类型、策略、状态 start
            rdaWorkflowObjectRel.setObjectTypeid(rdaWorkflowTempleteScope2.getObjectTypeid());
            rdaWorkflowObjectRel.setObjectPolicyid(rdaWorkflowTempleteScope2.getObjectPolicyid());
            rdaWorkflowObjectRel.setObjectStateid(rdaWorkflowTempleteScope2.getObjectStateid());
            //2022-01-17更改为取流程模板应用范围里的 类型、策略、状态 end
            rdaWorkflowObjectRel.setObjectModuleName(objectModuleName);
            rdaWorkflowObjectRel.setPurpose("approve");
            rdaWorkflowObjectRelMapper.insertRdaWorkflowObjectRel(rdaWorkflowObjectRel);
            //自动启动流程控制开关
            if("1".equals(rdaWorkflowTempleteScope2.getStartUp())){
                return documentStartUpWorkflowList(objectId);
            }
        }
        return AjaxResult.success();
    }

    /**
     *  克隆节点及关系
     */
    public int insertRdaWorkflow(RdaWorkflow rdaWorkflow,String url,String params) {
        int row=rdaWorkflowMapper.insertRdaWorkflow(rdaWorkflow);
//        new HistoryRecordUtil(sysHistoryService).recordHistory(rdaWorkflow.getId(),"创建",rdaWorkflow.getStateid(),"流程列表","");

        List<RdaNodeTemplete> list=rdaNodeTempleteMapper.selectRdaNodeTempleteByWorkflowid(rdaWorkflow.getFlowTempleteid());//查询流程模板节点表
        HashMap<Long,Long> map=new HashMap<Long,Long>();
        ArrayList<HashMap> idList=new ArrayList<HashMap>();
        if(list!=null) {
            for (RdaNodeTemplete rdaNodeTemplete : list) {
                //插入流程列表节点
                Long oldId = rdaNodeTemplete.getId();
                Long id = SnowFlakeUtils.nextId();
                map.put(oldId, id);
                idList.add(map);
                RdaWfNode rdaWfNode = new RdaWfNode();
                rdaWfNode.setId(id);
                rdaWfNode.setNodeName(rdaNodeTemplete.getNodeName());
                rdaWfNode.setDescription(rdaNodeTemplete.getDescription());
                rdaWfNode.setLevel(rdaNodeTemplete.getLevel());
                rdaWfNode.setWorkflowid(rdaWorkflow.getId());
                rdaWfNode.setAncestors(rdaNodeTemplete.getAncestors());
                rdaWfNode.setRdorder(rdaNodeTemplete.getRdorder());
                rdaWfNode.setUserId(rdaNodeTemplete.getUserId());
                rdaWfNode.setRoleId(rdaNodeTemplete.getRoleId());
                rdaWfNode.setUserName(rdaNodeTemplete.getUserName());
                rdaWfNode.setRoleName(rdaNodeTemplete.getRoleName());
                rdaWfNode.setCreateTime(DateUtils.getNowDate());
               /* rdaWfNode.setModifyTime(rdaNodeTemplete.getModifyTime());*/
                rdaWfNode.setOwnerid(SecurityUtils.getUserId());
                /*rdaWfNode.setTypeid(RdaWorkflowServiceImpl.typeid.intValue());
                rdaWfNode.setPolicyid(RdaWorkflowServiceImpl.policyid.intValue());
                rdaWfNode.setStateid(10000965);*/
                rdaWfNode.setTypeid(WorkflowStateid.wfNodeTypeid.intValue());
                rdaWfNode.setPolicyid(WorkflowStateid.wfNodePolicyid.intValue());
                rdaWfNode.setStateid(WorkflowStateid.wfNodeCreateid.intValue());
                rdaWfNode.setNodeType(rdaNodeTemplete.getNodeType());
                rdaWfNode.setUserandor(rdaNodeTemplete.getUserandor());
                rdaWfNode.setNodeandor(rdaNodeTemplete.getNodeandor());
                rdaWfNode.setRejectTostart(rdaNodeTemplete.isRejectTostart());
                rdaWfNode.setRejectToprevious(rdaNodeTemplete.isRejectToprevious());
                rdaWfNode.setRejectSkipComplete(rdaNodeTemplete.isRejectSkipComplete());
                rdaWfNode.setAppovedScript(rdaNodeTemplete.getAppovedScript());
                rdaWfNode.setRejectAutomatic(rdaNodeTemplete.isRejectAutomatic());
                rdaWfNode.setRejecttostartScript(rdaNodeTemplete.getRejecttostartScript());
                //2022-01-15 新增创建时间记录到流程节点表 start
                rdaWfNode.setCreateTime(DateUtils.getNowDate());
                //2022-01-15 新增创建时间记录到流程节点表 end
                //2022-01-24 新增是否允许撤回、是否允许委托 start
                rdaWfNode.setIsWithdraw(rdaNodeTemplete.getIsWithdraw());
                rdaWfNode.setIsAgent(rdaNodeTemplete.getIsAgent());
                //2022-01-24 新增是否允许撤回、是否允许委托 end
                //2022-01-28 新增记录流程模板id、流程模板节点id start
                rdaWfNode.setWorkflowtempleteid(rdaNodeTemplete.getWorkflowid());
                rdaWfNode.setWorkflowtempleteNodeid(rdaNodeTemplete.getId());
                //2022-01-28 新增记录流程模板id、流程模板节点id end
                //2022-02-15 新增xy轴坐标 start
                rdaWfNode.setX(rdaNodeTemplete.getX());
                rdaWfNode.setY(rdaNodeTemplete.getY());
                //2022-02-15 新增xyx轴坐标 end
                //2022-05-06 新增条件1~5 start
                rdaWfNode.setScript1(rdaNodeTemplete.getScript1());
                rdaWfNode.setScript2(rdaNodeTemplete.getScript2());
                rdaWfNode.setScript3(rdaNodeTemplete.getScript3());
                rdaWfNode.setScript4(rdaNodeTemplete.getScript4());
                rdaWfNode.setScript5(rdaNodeTemplete.getScript5());
                //2022-05-06 新增条件1~5 end
                //2022-11-07 新增邮箱
                rdaWfNode.setEmail(rdaNodeTemplete.getEmail());
                rdaWfNode.setUrl(url);
                rdaWfNode.setUrlParams(params);
                rdaWfNodeMapper.insertRdaWfNode(rdaWfNode);
            }


            List<RdaWorkflow2NodeTempleteRel> Rel_list=rdaWorkflow2NodeTempleteRelMapper.selectRdaNoderelTempleteByWorkflowid(rdaWorkflow.getFlowTempleteid());
            if(Rel_list!=null && Rel_list.size()!=0 ){

                for (RdaWorkflow2NodeTempleteRel rdaNodeRELTemplete:Rel_list) {
                    //插入流程列表节点
                    Long id = SnowFlakeUtils.nextId();
                    Long fromid=rdaNodeRELTemplete.getFromid();
                    Long toid=rdaNodeRELTemplete.getToid();
                    for (int i=0;i<idList.size();i++){
                        HashMap<Long,Long> relmap=idList.get(i);
                        for (Long key:relmap.keySet()) {
                            if(key.equals(fromid)){
                                fromid=map.get(key);
                            }
                            if(toid.equals(key)){
                                toid=map.get(key);
                            }
                        }

                    }
                    RdaWorkflow2NodeRel rdaWorkflow2NodeRel=new RdaWorkflow2NodeRel();
                    rdaWorkflow2NodeRel.setId(id);
                    rdaWorkflow2NodeRel.setFromid(fromid);
                    rdaWorkflow2NodeRel.setToid(toid);
                    rdaWorkflow2NodeRel.setWorkflowid(rdaWorkflow.getId());
                    rdaWorkflow2NodeRel.setOperationType(rdaNodeRELTemplete.getOperationType());
                    rdaWorkflow2NodeRel.setOperationState(rdaNodeRELTemplete.getOperationState());
                    rdaWorkflow2NodeRel.setRejectScript(rdaNodeRELTemplete.getRejectScript());
                    rdaWorkflow2NodeRel.setRoad(rdaNodeRELTemplete.getRoad());
                    rdaWorkflow2NodeRel.setRoadFlag(rdaNodeRELTemplete.getRoadFlag());
                    rdaWorkflow2NodeRel.setRoadAuto(rdaNodeRELTemplete.getRoadAuto());
                    rdaWorkflow2NodeRel.setRoadAttribute(rdaNodeRELTemplete.getRoadAttribute());
                    rdaWorkflow2NodeRel.setAppovedScript(rdaNodeRELTemplete.getAppovedScript());
                    rdaWorkflow2NodeRelMapper.insertRdaWorkflow2NodeRel(rdaWorkflow2NodeRel);
                }

            }
        }
        return row;
    }

    /**
     * 启动流程
     */
    public AjaxResult documentStartUpWorkflowList(Long objectid){
        RdaWorkflowObjectRel rdaWorkflowObjectRel=new RdaWorkflowObjectRel();
        rdaWorkflowObjectRel.setObjectid(Long.valueOf(objectid));
        List<RdaWorkflowObjectRel>  rdaWorkflowObjectRelList=rdaWorkflowObjectRelMapper.selectRdaWorkflowObjectRelList(rdaWorkflowObjectRel);//差个排序取最新数据根据时间排序
        Long[] Workflowids=new Long[1];
        if(!rdaWorkflowObjectRelList.isEmpty()){
            rdaWorkflowObjectRel=rdaWorkflowObjectRelList.get(0);
            String checkTips=objectCheck(rdaWorkflowObjectRel,"文档启动流程");
            if(!checkTips.isEmpty()){
                return AjaxResult.error(checkTips);
            }
            Workflowids[0]=rdaWorkflowObjectRel.getWorkflowid();
            RdaWorkflow getStateid=rdaWorkflowMapper.selectRdaWorkflowById(rdaWorkflowObjectRel.getWorkflowid());
            if(getStateid==null){
                return AjaxResult.error("启动失败当前无相关流程数据");
            }
            Long stateid=getStateid.getStateid().longValue();
            if(!stateid.equals(WorkflowStateid.workflowCreateid)){
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }

            RdaWfNode wfNode=new RdaWfNode();
            wfNode.setWorkflowid(rdaWorkflowObjectRel.getWorkflowid());
            wfNode.setNodeType(1);
            List<RdaWfNode> WfNodeList=rdaWfNodeMapper.selectRdaWfNodeList(wfNode);
            String nodeNames="";
            for(RdaWfNode rdaWfNode:WfNodeList){
                if(rdaWfNode.getUserId()==null || "".equals(rdaWfNode.getUserId())){
                    nodeNames+=rdaWfNode.getNodeName()+",";
                }
            }
            if(!nodeNames.isEmpty()){
                return AjaxResult.error("当前任务有节点未指定用户，自动启动失败，未设置用户的节点名有："+nodeNames.substring(0,nodeNames.lastIndexOf(",")));
            }
            return startUpWorkflowList(Workflowids);
        }
        return AjaxResult.error("自动启动失败当前无相关流程数据");
    }

    /**
     * 校验
     *
     * @param rdaWorkflowObjectRel 节点ID
     * @param module 功能模块名
     * @return 错误提示信息
     */
    public String objectCheck(RdaWorkflowObjectRel rdaWorkflowObjectRel,String module){
        String checkTips="";
        if("document".equals(rdaWorkflowObjectRel.getObjectModuleName())){
            HashMap<String,Object> document=dynamicService.selectDataById(tableName,rdaWorkflowObjectRel.getObjectid());
            if("文档启动流程".equals(module)){
                Long polisyId=Long.valueOf(document.get("policyid").toString());
                Long stateId=Long.valueOf(document.get("stateid").toString());
                Long objectPolisyId =rdaWorkflowObjectRel.getObjectPolicyid();
                Long objectStateId=rdaWorkflowObjectRel.getObjectStateid();
                if(polisyId.equals(objectPolisyId) && stateId.equals(objectStateId)){
                    checkTips="";
                }else{
                    checkTips="状态不满足流程自动启动条件";
                }
            }
        }
        return checkTips;
    }

    /**
     * 启动流程
     */
    public AjaxResult startUpWorkflowList(Long[] ids){
        for (int i=0;i<ids.length;i++) {
            RdaWorkflow getStateid = rdaWorkflowMapper.selectRdaWorkflowById(ids[i]);
            Long stateid = getStateid.getStateid().longValue();
            if (!stateid.equals(WorkflowStateid.workflowCreateid)) {
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }
            RdaWfNode wfNode = new RdaWfNode();
            wfNode.setWorkflowid(ids[i]);
            wfNode.setNodeType(1);
            List<RdaWfNode> WfNodeList = rdaWfNodeMapper.selectRdaWfNodeList(wfNode);
            String nodeNames = "";
            for (RdaWfNode rdaWfNode : WfNodeList) {
                if (rdaWfNode.getUserId() == null || "".equals(rdaWfNode.getUserId())) {
                    nodeNames += rdaWfNode.getNodeName() + ",";
                }
            }
            if (!nodeNames.isEmpty()) {
                return AjaxResult.error("当前任务有节点未指定用户，自动启动失败，未设置用户的节点名有：" + nodeNames.substring(0, nodeNames.lastIndexOf(",")));
            }

            RdaWorkflow rdaWorkflow = new RdaWorkflow();
            rdaWorkflow.setId(ids[i]);
            /*2021-12-19 以后要更换成动态**/
            rdaWorkflow.setStateid(WorkflowStateid.workflowActiveid.intValue());
            rdaWorkflow.setModifyTime(DateUtils.getNowDate());
            //把流程状态设置为活动
            rdaWorkflowMapper.updateRdaWorkflow(rdaWorkflow);
//            new HistoryRecordUtil(rdaStateService,sysHistoryService).lifeCycleHistory(rdaWorkflow.getId(),WorkflowStateid.workflowCreateid.intValue(),rdaWorkflow.getStateid(),"promote");

            //将流程开始节点设置为完成状态

            /*2021-12-19 以后要更换成动态**/
            rdaWfNodeMapper.updateRdaWfNodeByStateid(ids[i], WorkflowStateid.wfNodeCompleteid, 0L,DateUtils.getNowDate());
            //将下节点设置为活动状态

            RdaWfNode startNode = rdaWfNodeMapper.selectRdaWfNodeStartOrEnd(ids[i], 0l);
            RdaWorkflow2NodeRel rdaWorkflow2NodeRel = new RdaWorkflow2NodeRel();
            rdaWorkflow2NodeRel.setFromid(startNode.getId());
            List<RdaWorkflow2NodeRel> startList = rdaWorkflow2NodeRelMapper.selectRdaWorkflow2NodeRelList(rdaWorkflow2NodeRel);
            for (int j = 0; j < startList.size(); j++) {
                //更新开始节点下级节点为活动
                RdaWfNode modifyStateid = new RdaWfNode();
                modifyStateid.setId(startList.get(j).getToid());
                /*2021-12-19 以后要更换成动态**/
                modifyStateid.setStateid(WorkflowStateid.wfNodeActiveid.intValue());
                modifyStateid.setStartTime(DateUtils.getNowDate());
                rdaWfNodeMapper.updateRdaWfNode(modifyStateid);

                List<RdaWfNode> list = rdaWfNodeMapper.selectRdaWfNodebyUser(startList.get(j).getToid());
                if (list != null) {
                    for (RdaWfNode rdaWfNode : list) {
                        String[] userId=rdaWfNode.getUserId().split(",");
                        for(int k=0;k<userId.length;k++) {
                            String userIdK=userId[k];
                            Long userIdJ=Long.valueOf(userIdK);
                            SysUser user = userMapper.selectUserById(userIdJ);

                            RdaWfTask rdaWfTask = new RdaWfTask();
                            Long id = SnowFlakeUtils.nextId();
                            rdaWfTask.setId(id);
                            rdaWfTask.setWorkflowid(ids[i]);
                            rdaWfTask.setNodeid(rdaWfNode.getId());
                            //2022-02-11 通过流程启动判断该流程是否是全局委托 start
                            if (workflowAgent(rdaWfNode)) {
                                return AjaxResult.success();
                            }
                            //2022-02-11 通过流程启动判断该流程是否是全局委托 end
                            if (user != null) {
                                rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                                rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");
                            }
                            rdaWfTask.setUserId(userIdJ);
                            rdaWfTask.setOwnerid(SecurityUtils.getUserId());

                            rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                            rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                            rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                            rdaWfTask.setTransfer(false);
                            rdaWfTask.setOriginalId(userIdJ);
                            rdaWfTask.setCreateTime(DateUtils.getNowDate());
                            rdaWfTask.setStartTime(DateUtils.getNowDate());
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                            //还剩关系表未插入、待完成rda_node2_task_rel
                            RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                            rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                            rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                            rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                            rdaNode2TaskRelMapper.insertRdaNode2TaskRel(rdaNode2TaskRel);
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }


    //流程委托 优先级依次为：流程指定节点委托>流程模板委托>全局委托
    public boolean workflowAgent(RdaWfNode rdaWfNode){
        //指定节点委托
        if ("是".equals(rdaWfNode.getIsAgent())) {
            //则查找对应的模板id并通过流程委托关系表进行匹配，查找是否有对应的委托人；
            RdaWfNodeAgentRel rdaWfNodeAgentRel = new RdaWfNodeAgentRel();
            rdaWfNodeAgentRel.setWorkflowtempleteid(rdaWfNode.getWorkflowtempleteid());
            rdaWfNodeAgentRel.setTempleteNodeId(rdaWfNode.getWorkflowtempleteNodeid());
            rdaWfNodeAgentRel.setEndTime(DateUtils.getNowDate());
            List<RdaWfNodeAgentRel> rdaWfNodeAgentRelList = rdaWfNodeAgentRelMapper.selectRdaWfNodeAgentRelList(rdaWfNodeAgentRel);
            if(rdaWfNodeAgentRelList.size()!=0) {
                for (RdaWfNodeAgentRel wfNodeAgentRel : rdaWfNodeAgentRelList) {
                    //设置流程节点委托为激活状态
                    RdaWfNodeAgentRel nodeAgentRel=new RdaWfNodeAgentRel();
                    nodeAgentRel.setId(wfNodeAgentRel.getId());
                    nodeAgentRel.setStateid(WorkflowStateid.agentNodeActivation);
                    rdaWfNodeAgentRelMapper.updateRdaWfNodeAgentRel(nodeAgentRel);

                    Long agentUserId = wfNodeAgentRel.getAgentUserId();//委托人id
                    Long beagentUserId = wfNodeAgentRel.getBeagentUserId();//被委托人id

                    RdaWfTask rdaWfTask = new RdaWfTask();
                    Long id = SnowFlakeUtils.nextId();
                    rdaWfTask.setId(id);
                    rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                    rdaWfTask.setNodeid(rdaWfNode.getId());
                    rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                    rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                    rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                    rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                    rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                    rdaWfTask.setTransfer(false);
                    rdaWfTask.setCreateTime(DateUtils.getNowDate());
                    rdaWfTask.setStartTime(DateUtils.getNowDate());
                    if ("替代".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                        //将userid更改为委托人id
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("替代");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }

                    } else if ("抄送".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                        //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("抄送");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }

                    } else if ("同时处理".equals(wfNodeAgentRel.getAgentTypeid())) {
                        //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }


                    }

                    RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                    rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                    rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                    rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                    rdaNode2TaskRelMapper.insertRdaNode2TaskRel(rdaNode2TaskRel);
                }
                return true;
            }
            return false;
        }else{
            //全局委托之指定模板委托
            RdaWfUserAgent rdaWfUserAgent=new RdaWfUserAgent();
            rdaWfUserAgent.setWorkflowtempleteid(rdaWfNode.getWorkflowtempleteid());
            rdaWfUserAgent.setEndTime(DateUtils.getNowDate());
            List<RdaWfUserAgent> List=rdaWfUserAgentMapper.selectRdaWfUserAgentList(rdaWfUserAgent);
            if(List.size()!=0){
                for(RdaWfUserAgent wfUserAgent:List){
                    //设置全局委托为激活状态
                    RdaWfUserAgent userAgent=new RdaWfUserAgent();
                    userAgent.setId(wfUserAgent.getId());
                    userAgent.setStateid(WorkflowStateid.agentActivationid);
                    rdaWfUserAgentMapper.updateRdaWfUserAgent(userAgent);
                    Long agentUserId=wfUserAgent.getAgentUserId();//委托人id
                    Long beagentUserId=wfUserAgent.getBeagentUserId();//被委托人id

                    RdaWfTask rdaWfTask = new RdaWfTask();
                    Long id = SnowFlakeUtils.nextId();
                    rdaWfTask.setId(id);
                    rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                    rdaWfTask.setNodeid(rdaWfNode.getId());
                    rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                    rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                    rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                    rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                    rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                    rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                    rdaWfTask.setTransfer(false);
                    rdaWfTask.setCreateTime(DateUtils.getNowDate());
                    rdaWfTask.setStartTime(DateUtils.getNowDate());

                    if ("替代".equals(wfUserAgent.getAgentTypeid())) {
                        //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                        //将userid更改为委托人id
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("替代");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }

                    }else if ("抄送".equals(wfUserAgent.getAgentTypeid())) {
                        //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                        //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("抄送");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }

                    }else if ("同时处理".equals(wfUserAgent.getAgentTypeid())) {
                        //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                        String userIdI[]=rdaWfNode.getUserId().split(",");
                        for(int i=0;i<userIdI.length;i++){
                            String userIdJ=userIdI[i];
                            Long userId=Long.valueOf(userIdJ);
                            rdaWfTask.setUserId(agentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                            rdaWfTask.setId(SnowFlakeUtils.nextId());
                            rdaWfTask.setUserId(beagentUserId);
                            rdaWfTask.setOriginalId(userId);
                            rdaWfTask.setAgentTypeid("同时处理");
                            rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                        }
                    }

                    RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                    rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                    rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                    rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                    rdaNode2TaskRelMapper.insertRdaNode2TaskRel(rdaNode2TaskRel);
                }
                return true;
            }else{
                //全局委托
                List<RdaWfUserAgent> rdaWfUserAgentList=rdaWfUserAgentMapper.selectRdaWfUserAgentByWorkflowtempleteid();
                if(rdaWfUserAgentList.size()!=0){
                    for(RdaWfUserAgent wfUserAgent:rdaWfUserAgentList){
                        //设置全局委托为激活状态
                        RdaWfUserAgent userAgent=new RdaWfUserAgent();
                        userAgent.setId(wfUserAgent.getId());
                        userAgent.setStateid(WorkflowStateid.agentActivationid);
                        rdaWfUserAgentMapper.updateRdaWfUserAgent(userAgent);
                        Long agentUserId=wfUserAgent.getAgentUserId();//委托人id
                        Long beagentUserId=wfUserAgent.getBeagentUserId();//被委托人id

                        RdaWfTask rdaWfTask = new RdaWfTask();
                        Long id = SnowFlakeUtils.nextId();
                        rdaWfTask.setId(id);
                        rdaWfTask.setWorkflowid(rdaWfNode.getWorkflowid());
                        rdaWfTask.setNodeid(rdaWfNode.getId());
                        rdaWfTask.setTaskName(rdaWfNode.getNodeName() + "的任务");
                        rdaWfTask.setDescription(rdaWfNode.getNodeName() + "的任务");

                        rdaWfTask.setOwnerid(SecurityUtils.getUserId());
                        rdaWfTask.setTypeid(WorkflowStateid.wfTaskTypeid);
                        rdaWfTask.setPolicyid(WorkflowStateid.wfTaskPolicyid);
                        rdaWfTask.setStateid(WorkflowStateid.wfTaskActiveid);
                        rdaWfTask.setTransfer(false);
                        rdaWfTask.setCreateTime(DateUtils.getNowDate());
                        rdaWfTask.setStartTime(DateUtils.getNowDate());

                        if ("替代".equals(wfUserAgent.getAgentTypeid())) {
                            //流程任务直接发送给委托人，被委托人不需要看到和处理（一条任务）；
                            //将userid更改为委托人id
                            String userIdI[]=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                String userIdJ=userIdI[i];
                                Long userId=Long.valueOf(userIdJ);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("替代");
                                rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                            }

                        }else if ("抄送".equals(wfUserAgent.getAgentTypeid())) {
                            //抄送：流程任务直接发送给委托人，被委托人可以看到不需要处理（两个任务，被委托人的任务不需要也不能处理，委托人任务处理完成后被委托人任务自动完成）；
                            //生成一条委托人任务跟一条被委托人任务，被委托人任务用代理类型抄送来区分
                            String userIdI[]=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                String userIdJ=userIdI[i];
                                Long userId=Long.valueOf(userIdJ);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                                rdaWfTask.setId(SnowFlakeUtils.nextId());
                                rdaWfTask.setUserId(beagentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("抄送");
                                rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                            }

                        }else if ("同时处理".equals(wfUserAgent.getAgentTypeid())) {
                            //被委托人和委托人可以同时处理，只要有一个处理完成就可以完成（两个并行的or任务）；
                            String userIdI[]=rdaWfNode.getUserId().split(",");
                            for(int i=0;i<userIdI.length;i++){
                                String userIdJ=userIdI[i];
                                Long userId=Long.valueOf(userIdJ);
                                rdaWfTask.setUserId(agentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("同时处理");
                                rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);

                                rdaWfTask.setId(SnowFlakeUtils.nextId());
                                rdaWfTask.setUserId(beagentUserId);
                                rdaWfTask.setOriginalId(userId);
                                rdaWfTask.setAgentTypeid("同时处理");
                                rdaWfTaskMapper.insertRdaWfTask(rdaWfTask);
                            }

                        }

                        RdaNode2TaskRel rdaNode2TaskRel = new RdaNode2TaskRel();
                        rdaNode2TaskRel.setId(SnowFlakeUtils.nextId());
                        rdaNode2TaskRel.setTaskid(rdaWfTask.getId());
                        rdaNode2TaskRel.setNodeid(rdaWfNode.getId());
                        rdaNode2TaskRelMapper.insertRdaNode2TaskRel(rdaNode2TaskRel);
                    }
                    return true;
                }
                return false;
            }
        }
    }
}
